package org.lonetree.tc.webapp.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.ElectronicSource;
import org.lonetree.tc.core.PhysicalSource;
import org.lonetree.tc.core.Source;
import org.lonetree.tc.core.UserSource;
import org.lonetree.tc.core.Book.Isbn;
import org.lonetree.tc.core.ElectronicSource.Url;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.webapp.forms.SourceForm;


public class CommitSource extends SecureAction{

	@Override
	protected ActionForward executeSecure(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		
		try{
			SourceForm s = (SourceForm)form;
			String isbn = s.getIsbn();
			if(isbn == null){
				new NullPointerException("isbn parameter is null").printStackTrace();
				return mapping.findForward("failure");
			}
			
			BookDAO bdao = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY).getBookDAO();
			Book book = bdao.getBook(new Isbn(isbn));
			String type = s.getType();
			s.getDescription();
			s.getLocation();
			s.getName();
			s.getPrice();
			Source source;
			if(type.equals("user")){
				source = new UserSource(book, s.getPrice(), s.getDescription(), getCurrentUser());
			}
			else if(type.equals("physical")){
				source = new PhysicalSource(book, s.getName(), s.getPrice(), s.getDescription(), s.getLocation());
			}
			else if(type.equals("online")){
				source = new ElectronicSource(book, s.getName(), s.getPrice(), s.getDescription(), new Url(s.getLocation()));
			}
			else{
				return mapping.findForward("failure");
			}
			
			request.setAttribute("book", book);
			bdao.updateBook(book);
			return mapping.findForward("success");
		}
		catch(Exception e){
			e.printStackTrace();
			return mapping.findForward("success");
		}
	}

}
